package com.tang.elasticsearchdemo;

import com.alibaba.fastjson.JSON;
import com.tang.elasticsearchdemo.domain.Goods;
import com.tang.elasticsearchdemo.mapper.GoodsMapper;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest
class ElasticsearchDemoApplicationTests2 {

    @Autowired
    private RestHighLevelClient cilent;


    @Autowired
    private GoodsMapper goodsMapper;

    /*
    * 批量操作
    * */
    public void testBulk() throws IOException {
        //创建bulkrequest对象,整合所有操作(增删改查)
        BulkRequest bulkRequest = new BulkRequest();

        /*
        * 删除5号记录
        * 2.添加8号记录
        * 3.修改2号记录
        * */

        //添加对应操作
        //1. 删除1号记录
        DeleteRequest deleteRequest = new DeleteRequest("person","1");
        bulkRequest.add(deleteRequest);

        //2. 添加6号记录
        Map map = new HashMap();
        map.put("name","六号");
        IndexRequest indexRequest = new IndexRequest("person").id("6").source(map);
        bulkRequest.add(indexRequest);


        Map map2 = new HashMap();
        map2.put("name","三号");

        //3. 修改3号记录 名称为 “三号”
        UpdateRequest updateReqeust = new UpdateRequest("person","3").doc(map2);
        bulkRequest.add(updateReqeust);

        //执行批量操作
        cilent.bulk(bulkRequest, RequestOptions.DEFAULT);

    }

    /**
     * 批量导入
     */

    @Test
    public void importData() throws IOException {

/*        //查询数据库,拿到goods的全部信息
        List<Goods> goods = goodsMapper.findAll();
       // System.out.println(goods);

        //2. bulk导入
        BulkRequest bulkRequest = new BulkRequest();

        //3.循环gooods 创建INindexRquest添加数据
        for (Goods good : goods) {
            //设置spec规格的数据信息,map的数据
          //  good.setSpec(JSON.parseObject(good.getSpecStr(),Map.class));
            IndexRequest indexRequest = new IndexRequest("goods");
            indexRequest.id(good.getId()+"").source(JSON.toJSONString(good), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        cilent.bulk(bulkRequest,RequestOptions.DEFAULT);*/

        //1.查询所有数据，mysql
        List<Goods> goodsList = goodsMapper.findAll();

        //System.out.println(goodsList.size());
        //2.bulk导入
        BulkRequest bulkRequest = new BulkRequest();

        //2.1 循环goodsList，创建IndexRequest添加数据
        for (Goods goods : goodsList) {
            //2.2 设置spec规格信息 Map的数据   specStr:{}
            //goods.setSpec(JSON.parseObject(goods.getSpecStr(),Map.class));

            String specStr = goods.getSpecStr();
            //将json格式字符串转为Map集合
            Map map = JSON.parseObject(specStr, Map.class);
            //设置spec map
            goods.setSpec(map);
            //将goods对象转换为json字符串
            String data = JSON.toJSONString(goods);//map --> {}
            IndexRequest indexRequest = new IndexRequest("goods");
            indexRequest.id(goods.getId()+"").source(data, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }


        BulkResponse response = cilent.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(response.status());
    }

    /**
     * 查询所有
     *  1. matchAll
     *  2. 将查询结果封装为Goods对象，装载到List中
     *  3. 分页。默认显示10条
     */
    @Test
    public void testMatchAll() throws IOException {
        //2.构建查询对象,指定查询的索引名称
        SearchRequest searchRequest = new SearchRequest("goods");

        //4. 创建查询条件构建器SearchSourceBuilder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //6. 查询条件
        QueryBuilder query = QueryBuilders.matchAllQuery();//查询所有文档

        //5. 指定查询条件
        sourceBuilder.query(query);

        //3. 添加查询条件构建器 SearchSourceBuilder
        searchRequest.source(sourceBuilder);

        // 8 . 添加分页信息
        sourceBuilder.from(0);//开始索引
        sourceBuilder.size(100);//结束索引

        //1.获取查询结果
        SearchResponse searchResponse =  cilent.search(searchRequest,RequestOptions.DEFAULT);

        //7. 获取命中对象 SearchHits(意思是查询的数据)
        SearchHits searchHits = searchResponse.getHits();
        //7.1 获取总记录数
        long value = searchHits.getTotalHits().value;
        System.out.println("总记录数："+value);

        List<Goods> goodsList = new ArrayList<>();
        //7.2 获取Hits数据  数组
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            //获取json字符串格式的数据
            String sourceAsString = hit.getSourceAsString();
            //转为java对象
            Goods goods = JSON.parseObject(sourceAsString, Goods.class);

            goodsList.add(goods);
        }

        for (Goods goods : goodsList) {
            System.out.println(goods);
        }
    }

/*
* term : 分词查询
* */
@Test
public void testTermQuery() throws IOException {

    SearchRequest searchRequest =  new SearchRequest("goods");

    //4. 创建查询条件构建器SearchSourceBuilder
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

    QueryBuilder query = QueryBuilders.termQuery("title","华"); //term词条查询
    sourceBuilder.query(query);
    searchRequest.source(sourceBuilder);

    //1.获取查询结果
    SearchResponse search = cilent.search(searchRequest, RequestOptions.DEFAULT);
    SearchHits searchhits = search.getHits();

    //获取记录数
    long value = searchhits.getTotalHits().value; //拿到是记录数
    System.out.println("总记录条数为:"+value);

    List<Goods> goodslist =  new ArrayList();
    //封装成对应的java对象
    SearchHit[] hits = searchhits.getHits();
    for (SearchHit hit : hits) {
        String sourceAsString = hit.getSourceAsString();
        //转为json
        Goods goods = JSON.parseObject(sourceAsString, Goods.class);
        goodslist.add(goods);
    }

    for (Goods o : goodslist) {
        System.out.println(o);
    }


}

    /*
     * matchQuery : 全文查询
     * */
    @Test
    public void testmatchQuery() throws IOException {

        SearchRequest searchRequest =  new SearchRequest("goods");

        //4. 创建查询条件构建器SearchSourceBuilder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        QueryBuilder query = QueryBuilders.matchQuery("title","华为手机"); //term词条查询

        //MatchQueryBuilder 这是QueryBuilder它的父类 需要强转
        ((MatchQueryBuilder) query).operator(Operator.AND); //分词后的查询条件一起满足

        sourceBuilder.query(query);
        searchRequest.source(sourceBuilder);

        //1.获取查询结果
        SearchResponse search = cilent.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchhits = search.getHits();

        //获取记录数
        long value = searchhits.getTotalHits().value; //拿到是记录数
        System.out.println("总记录条数为:"+value);

        List<Goods> goodslist =  new ArrayList();
        //封装成对应的java对象
        SearchHit[] hits = searchhits.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            //转为json
            Goods goods = JSON.parseObject(sourceAsString, Goods.class);
            goodslist.add(goods);
        }

        for (Goods o : goodslist) {
            System.out.println(o);
        }


    }



    /*
   #wildcard  查询条件分词 模糊查询
     * */
    @Test
    public void testwildcardQuery() throws IOException {

        SearchRequest searchRequest =  new SearchRequest("goods");

        //4. 创建查询条件构建器SearchSourceBuilder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        QueryBuilder query = QueryBuilders.wildcardQuery("title","华为手机"); //term词条查询

        //MatchQueryBuilder 这是QueryBuilder它的父类 需要强转
        ((MatchQueryBuilder) query).operator(Operator.AND); //分词后的查询条件一起满足

        sourceBuilder.query(query);
        searchRequest.source(sourceBuilder);

        //1.获取查询结果
        SearchResponse search = cilent.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchhits = search.getHits();

        //获取记录数
        long value = searchhits.getTotalHits().value; //拿到是记录数
        System.out.println("总记录条数为:"+value);

        List<Goods> goodslist =  new ArrayList();
        //封装成对应的java对象
        SearchHit[] hits = searchhits.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            //转为json
            Goods goods = JSON.parseObject(sourceAsString, Goods.class);
            goodslist.add(goods);
        }

        for (Goods o : goodslist) {
            System.out.println(o);
        }


    }

    /*
#Regex  正则查询
 * */
    @Test
    public void testRegexQuery() throws IOException {

        SearchRequest searchRequest =  new SearchRequest("goods");

        //4. 创建查询条件构建器SearchSourceBuilder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        QueryBuilder query = QueryBuilders.regexpQuery("title","\\w+(.)*"); //term词条查询

        //MatchQueryBuilder 这是QueryBuilder它的父类 需要强转
        ((MatchQueryBuilder) query).operator(Operator.AND); //分词后的查询条件一起满足

        sourceBuilder.query(query);
        searchRequest.source(sourceBuilder);

        //1.获取查询结果
        SearchResponse search = cilent.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchhits = search.getHits();

        //获取记录数
        long value = searchhits.getTotalHits().value; //拿到是记录数
        System.out.println("总记录条数为:"+value);

        List<Goods> goodslist =  new ArrayList();
        //封装成对应的java对象
        SearchHit[] hits = searchhits.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            //转为json
            Goods goods = JSON.parseObject(sourceAsString, Goods.class);
            goodslist.add(goods);
        }

        for (Goods o : goodslist) {
            System.out.println(o);
        }


    }

    /*
#Regex  正则查询
* */
    @Test
    public void testprefixQuery() throws IOException {

        SearchRequest searchRequest =  new SearchRequest("goods");

        //4. 创建查询条件构建器SearchSourceBuilder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        QueryBuilder query = QueryBuilders.prefixQuery("bramdName","三"); //term词条查询

        //MatchQueryBuilder 这是QueryBuilder它的父类 需要强转
        ((MatchQueryBuilder) query).operator(Operator.AND); //分词后的查询条件一起满足

        sourceBuilder.query(query);
        searchRequest.source(sourceBuilder);

        //1.获取查询结果
        SearchResponse search = cilent.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchhits = search.getHits();

        //获取记录数
        long value = searchhits.getTotalHits().value; //拿到是记录数
        System.out.println("总记录条数为:"+value);

        List<Goods> goodslist =  new ArrayList();
        //封装成对应的java对象
        SearchHit[] hits = searchhits.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            //转为json
            Goods goods = JSON.parseObject(sourceAsString, Goods.class);
            goodslist.add(goods);
        }

        for (Goods o : goodslist) {
            System.out.println(o);
        }


    }

    /*
#Regex 范围排序查询
* */
    @Test
    public void testregexQuery() throws IOException {

        SearchRequest searchRequest =  new SearchRequest("goods");

        //4. 创建查询条件构建器SearchSourceBuilder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //范围查询
        RangeQueryBuilder query = QueryBuilders.rangeQuery("price");//term词条查询

        //指定下限
        query.gte(2000); //>=
        //指定上限
        query.lte(3000);  //<=

        sourceBuilder.query(query);

        sourceBuilder.sort("price", SortOrder.ASC);
        searchRequest.source(sourceBuilder);

        //1.获取查询结果
        SearchResponse search = cilent.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchhits = search.getHits();

        //获取记录数
        long value = searchhits.getTotalHits().value; //拿到是记录数
        System.out.println("总记录条数为:"+value);

        List<Goods> goodslist =  new ArrayList();
        //封装成对应的java对象
        SearchHit[] hits = searchhits.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            //转为json
            Goods goods = JSON.parseObject(sourceAsString, Goods.class);
            goodslist.add(goods);
        }

        for (Goods o : goodslist) {
            System.out.println(o);
        }

    }

    /*
#querystring 范围排序查询
* */
    @Test
    public void testquerystringQuery() throws IOException {

        SearchRequest searchRequest =  new SearchRequest("goods");

        //4. 创建查询条件构建器SearchSourceBuilder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //范围查询
        QueryStringQueryBuilder query = QueryBuilders.queryStringQuery("华为").field("title").field("categoryName").field("brandName");//term词条查询

        sourceBuilder.query(query);

        sourceBuilder.sort("price", SortOrder.ASC);
        searchRequest.source(sourceBuilder);

        //1.获取查询结果
        SearchResponse search = cilent.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchhits = search.getHits();

        //获取记录数
        long value = searchhits.getTotalHits().value; //拿到是记录数
        System.out.println("总记录条数为:"+value);

        List<Goods> goodslist =  new ArrayList();
        //封装成对应的java对象
        SearchHit[] hits = searchhits.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            //转为json
            Goods goods = JSON.parseObject(sourceAsString, Goods.class);
            goodslist.add(goods);
        }

        for (Goods o : goodslist) {
            System.out.println(o);
        }

    }

    /*
#bool 布尔查询: boolQuery.
    1.查询品牌为华为,
    2.查询标题包含:手机
    3.查询价格在:2000-3000
* */
    @Test
    public void testboolQuery() throws IOException {

        SearchRequest searchRequest =  new SearchRequest("goods");

        //4. 创建查询条件构建器SearchSourceBuilder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //1构建boolQuery
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        //2.构建个个查询条件
        //查询标题为华为
        QueryBuilder termquery =QueryBuilders.termQuery("brandName","华");
        query.must(termquery);

        //2.2查询标题包含手机
        QueryBuilder matchQuery = QueryBuilders.matchQuery("title", "手");
        query.filter(matchQuery);

        //3.查询价格在:2000-3000
         QueryBuilder range = QueryBuilders.rangeQuery("price");
        ((RangeQueryBuilder) range).lte(3000);   //上限
        ((RangeQueryBuilder) range).gte(2000); //下线
        query.must(range);

        //3.使用boolQuery查询
        sourceBuilder.query(query);

        sourceBuilder.sort("price", SortOrder.ASC);
        searchRequest.source(sourceBuilder);

        //1.获取查询结果
        SearchResponse search = cilent.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchhits = search.getHits();

        //获取记录数
        long value = searchhits.getTotalHits().value; //拿到是记录数
        System.out.println("总记录条数为:"+value);

        List<Goods> goodslist =  new ArrayList();
        //封装成对应的java对象
        SearchHit[] hits = searchhits.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            //转为json
            Goods goods = JSON.parseObject(sourceAsString, Goods.class);
            goodslist.add(goods);
        }

        for (Goods o : goodslist) {
            System.out.println(o);
        }

    }

    /**
     * 聚合查询：桶聚合，分组查询
     * 1. 查询title包含手机的数据
     * 2. 查询品牌列表
     */
    @Test
    public void testAggQuery() throws IOException {


        SearchRequest searchRequest = new SearchRequest("goods");

        SearchSourceBuilder sourceBulider = new SearchSourceBuilder();

        // 1. 查询title包含手机的数据
        MatchQueryBuilder query = QueryBuilders.matchQuery("title", "手机");

        sourceBulider.query(query);

        // 2. 查询品牌列表
        /*
        参数：
            1. 自定义的名称，将来用于获取数据
            2. 分组的字段
         */
        AggregationBuilder agg = AggregationBuilders.terms("goods_brands").field("brandName").size(100);
        sourceBulider.aggregation(agg);



        searchRequest.source(sourceBulider);


        SearchResponse searchResponse = cilent.search(searchRequest, RequestOptions.DEFAULT);


        SearchHits searchHits = searchResponse.getHits();
        //获取记录数
        long value = searchHits.getTotalHits().value;
        System.out.println("总记录数："+value);

        List<Goods> goodsList = new ArrayList<>();
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();

            //转为java
            Goods goods = JSON.parseObject(sourceAsString, Goods.class);

            goodsList.add(goods);
        }

        for (Goods goods : goodsList) {
            System.out.println(goods);
        }

        // 获取聚合结果
        Aggregations aggregations = searchResponse.getAggregations();

        Map<String, Aggregation> aggregationMap = aggregations.asMap();

        //System.out.println(aggregationMap);
        Terms goods_brands = (Terms) aggregationMap.get("goods_brands");

        List<? extends Terms.Bucket> buckets = goods_brands.getBuckets();

        List brands = new ArrayList();
        for (Terms.Bucket bucket : buckets) {
            Object key = bucket.getKey();
            brands.add(key);
        }

        for (Object brand : brands) {
            System.out.println(brand);
        }

    }


    /**
     *
     * 高亮查询：
     *  1. 设置高亮
     *      * 高亮字段
     *      * 前缀
     *      * 后缀
     *  2. 将高亮了的字段数据，替换原有数据
     */
    @Test
    public void testHighLightQuery() throws IOException {


        SearchRequest searchRequest = new SearchRequest("goods");

        SearchSourceBuilder sourceBulider = new SearchSourceBuilder();

        // 1. 查询title包含手机的数据
        MatchQueryBuilder query = QueryBuilders.matchQuery("title", "手机");

        sourceBulider.query(query);

        //设置高亮
        HighlightBuilder highlighter = new HighlightBuilder();
        //设置三要素
        highlighter.field("title");
        highlighter.preTags("<font color='red'>");
        highlighter.postTags("</font>");


        sourceBulider.highlighter(highlighter);



        // 2. 查询品牌列表
        /*
        参数：
            1. 自定义的名称，将来用于获取数据
            2. 分组的字段
         */
        AggregationBuilder agg = AggregationBuilders.terms("goods_brands").field("brandName").size(100);
        sourceBulider.aggregation(agg);



        searchRequest.source(sourceBulider);


        SearchResponse searchResponse = cilent.search(searchRequest, RequestOptions.DEFAULT);


        SearchHits searchHits = searchResponse.getHits();
        //获取记录数
        long value = searchHits.getTotalHits().value;
        System.out.println("总记录数："+value);

        List<Goods> goodsList = new ArrayList<>();
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();

            //转为java
            Goods goods = JSON.parseObject(sourceAsString, Goods.class);

            // 获取高亮结果，替换goods中的title
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField HighlightField = highlightFields.get("title");
            Text[] fragments = HighlightField.fragments();
            //替换
            goods.setTitle(fragments[0].toString());


            goodsList.add(goods);
        }

        for (Goods goods : goodsList) {
            System.out.println(goods);
        }

        // 获取聚合结果
        Aggregations aggregations = searchResponse.getAggregations();

        Map<String, Aggregation> aggregationMap = aggregations.asMap();

        //System.out.println(aggregationMap);
        Terms goods_brands = (Terms) aggregationMap.get("goods_brands");

        List<? extends Terms.Bucket> buckets = goods_brands.getBuckets();

        List brands = new ArrayList();
        for (Terms.Bucket bucket : buckets) {
            Object key = bucket.getKey();
            brands.add(key);
        }

        for (Object brand : brands) {
            System.out.println(brand);
        }

    }




}
